<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\MissionDeposit;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use Illuminate\Http\Request;

class MissionDepositForm extends Form
{
    public function handle(array $input)
    {
        $percentage = $input['percentage'];
        if ($percentage < 0 || $percentage > 100) {
            return $this->response()->error('数据错误');
        }
        $school_id = Admin::user()->school_id;
        $missionDeposit = \App\Models\MissionDeposit::where('school_id', $school_id)->first();
        if ($missionDeposit) {
            $missionDeposit->percentage = $percentage;
            $missionDeposit->save();
        }
        return $this->response()->success('操作成功')->refresh();
    }

    // 构建表单
    public function form()
    {
        $school_id = Admin::user()->school_id;
        $missionDeposit = \App\Models\MissionDeposit::where('school_id', $school_id)->first();
        if ($missionDeposit) {
            $this->number('percentage')->value($missionDeposit->percentage)->required();
        } else {
            \App\Models\MissionDeposit::with(['school'])->get()->map(function ($item) {

                $this->column(6, function (Form $form) use ($item) {
                    $form->text('name')->value($item->school->name)->readOnly();
                });
                $this->column(6, function (Form $form) use ($item) {
                    $form->text('percentage')->value($item->percentage)->readOnly();
                });
            });
            $this->disableSubmitButton();
        }
        $this->disableResetButton();
    }
}
